package com.xinyue.game.client.command;

import com.xinyue.game.client.network.GameClient;
import com.xinyue.network.codec.IGameMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;


/**
 * @author 王广帅
 * @date 2021年01月28日 12:08 上午
 */
@ShellComponent
public class GameClientNetworkCommand {
    private static Logger logger = LoggerFactory.getLogger(GameClientNetworkCommand.class);

    @Autowired
    private ApplicationContext context;
    public static GameClient gameClient;


    @ShellMethod("连接服务器")
    public void connectServer(@ShellOption(defaultValue = "localhost") String host, @ShellOption(defaultValue = "8088") int port) {
        if (gameClient != null) {
            gameClient.disconnect();
        }
        gameClient = new GameClient(context);
        gameClient.startConnectServer(host, port);
    }

    @ShellMethod("断开连当前连接")
    public String disconnect() {
        if (gameClient == null) {
            return "当前无连接！！";
        } else {
            gameClient.disconnect();
            return "断开连接成功";
        }
    }

    public static void sendMessage(IGameMessage gameMessage) {
        if (gameClient != null) {
            gameClient.sendMessage(gameMessage);
        } else {
            logger.error("消息发送失败,客户端与服务器未建立连接!");
        }
    }
}
